import * as React from 'react';
import { addLocaleData, IntlProvider } from 'react-intl';
import { LocaleProvider, message } from 'antd'
import { applyMiddleware } from 'redux';
import { createCookieMiddleware } from 'redux-cookie';
import { autoRehydrate } from 'redux-persist';
import dva from 'dva';
import { browserHistory, RouterContext } from 'dva/router'
// 引入dva-loading
import * as createLoading from 'dva-loading';
// 加载router
import router from '../src/router';
// 加载model
import { app as appModel, login, user } from '../src/models';
// 加载Logger
import { Logger, settings, lodash as _ } from '../src/utils';
import { getLocale } from '../src/utils/i18n';

// logger
const logger = Logger.get('render_createApp');
export default function createApp(opts, isServer=false, cookies = {}) {
  // 新建dva对象
  opts = _.assign(opts)({
      ...createLoading({
        effects: true
      }),
      onError (error) {
        // error的时候终止loadingMessage
        settings.hideLoadingMsg();
        message.error(error.message);
      },
      extraEnhancers: [
        applyMiddleware(createCookieMiddleware(cookies)),
        autoRehydrate(),
      ],
    });
  const app = dva(opts);

  // 设置model
  app.model(appModel);
  app.model(login);
  app.model(user);

  // i18n
  const appLocale = getLocale('zh');
  addLocaleData(appLocale.data);

  if (isServer) {
    app.router(({ history, app, ...extraArgs}) => {
      const { renderProps } = extraArgs as any;
      return (
        <LocaleProvider locale={appLocale.antd}>
          <IntlProvider locale={appLocale.locale} messages={appLocale.messages}>
            <RouterContext {...renderProps}/>
          </IntlProvider>
        </LocaleProvider>
      );
    });
  } else {
    app.router(router);
  }
  return app;
}
